package com.sense.kukoo.common.wiget.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.widget.AppCompatSeekBar
import androidx.cardview.widget.CardView
import androidx.constraintlayout.widget.ConstraintLayout
import com.alibaba.android.arouter.launcher.ARouter
import com.sense.feel.common.utils.ToastUtils
import com.sense.kukoo.common.R
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.event.LoginSuccessEvent
import com.sense.kukoo.common.event.LogoutEvent
import com.sense.kukoo.common.event.SubscriptionChangedEvent
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.media.watcher.UserWatcher
import com.sense.kukoo.common.repo.Repo.login
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.lib_logger.LoggerManager
import com.sense.kukoo.lib_picture.config.GlideConfig
import com.sense.kukoo.lib_picture.loader.Monet
import kotlinx.coroutines.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.IOException
import java.lang.Runnable

/*
class MediaControlerDialog(context:Context) : Dialog(context) {

    private val TAG: String = javaClass.simpleName
    private val dp16 = ApplicationContext.dp2px(16F)

    private lateinit var root: ConstraintLayout
    private lateinit var iv_back:ImageView
    private lateinit var iv_share: ImageView
    private lateinit var iv_music_icon:ImageView
    private lateinit var seek_bar: AppCompatSeekBar
    private lateinit var tv_title: TextView
    private lateinit var tv_title_first: TextView
    private lateinit var bg_btn_subscribe: ImageView
    private lateinit var tv_time_current: TextView
    private lateinit var tv_time_total: TextView
    private lateinit var card_view: CardView

    private lateinit var iv_btn_backward: ImageView
    private lateinit var iv_btn_play: ImageView
    private lateinit var iv_btn_forward: ImageView
    private lateinit var iv_btn_playlist: ImageView
    private lateinit var tv_btn_times: TextView
    private lateinit var ll_btn_timer: View
    private lateinit var iv_btn_timer: ImageView
    private lateinit var iv_btn_timer_text: TextView
    private lateinit var iv_btn_heart: ImageView

    private lateinit var drawable_thumb_red: Drawable
    private lateinit var drawable_thumb_black: Drawable
    private lateinit var drawable_progress_red: Drawable
    private lateinit var drawable_progress_black: Drawable

    private val mAnimHeight:Float = 800f
    private val mAnimTime:Long = 300

    private var state = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING
    private var speed: Float = UserWatcher.MusicStateWatcher.SPEED_1P0
    private var isSeekBarTracking = false
    private var isSubscribe:Boolean = false
    private var isLike:Boolean = false
    private lateinit var mCurrentMusic: LocalMediaListItemBean

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        context.setTheme(R.style.bottom_media_dialog)
        setContentView(R.layout.common_dialog_media_controler)
        //
        root = findViewById<ConstraintLayout>(R.id.root)
        //
        iv_back = findViewById<ImageView>(R.id.iv_back)
        iv_share = findViewById<ImageView>(R.id.iv_share)
        iv_music_icon = findViewById<ImageView>(R.id.iv_music_icon)
        seek_bar = findViewById<AppCompatSeekBar>(R.id.seek_bar)
        iv_btn_backward = findViewById<ImageView>(R.id.iv_btn_backward)
        iv_btn_play = findViewById<ImageView>(R.id.iv_btn_play)
        iv_btn_forward = findViewById<ImageView>(R.id.iv_btn_forward)
        iv_btn_playlist = findViewById<ImageView>(R.id.iv_btn_playlist)
        tv_btn_times = findViewById<TextView>(R.id.tv_btn_times)
        ll_btn_timer = findViewById<View>(R.id.ll_btn_timer)
        iv_btn_timer = findViewById<ImageView>(R.id.iv_btn_timer)
        iv_btn_timer_text = findViewById<TextView>(R.id.iv_btn_timer_text)
        iv_btn_heart = findViewById<ImageView>(R.id.iv_btn_heart)
        card_view = findViewById<CardView>(R.id.card_view)

        tv_title = findViewById<TextView>(R.id.tv_title)
        tv_title_first = findViewById<TextView>(R.id.tv_title_first)
        bg_btn_subscribe = findViewById<ImageView>(R.id.bg_btn_subscribe)
        tv_time_current = findViewById<TextView>(R.id.tv_time_current)
        tv_time_total = findViewById<TextView>(R.id.tv_time_total)
        //
        drawable_thumb_red = ApplicationContext.getResources().getDrawable(R.drawable.common_icon_seekbar_thumb_red)
        drawable_thumb_black = ApplicationContext.getResources().getDrawable(R.drawable.common_icon_seekbar_thumb_black)
        drawable_progress_red = ApplicationContext.getResources().getDrawable(R.drawable.common_layer_seekbar_progress_red)
        drawable_progress_black = ApplicationContext.getResources().getDrawable(R.drawable.common_layer_seekbar_progress_black)
        //
        iv_back.setOnClickListener {
            dismiss()
        }
        iv_share.setOnClickListener {
            val alias : String = mCurrentMusic.titleOfChapter()
            val type : Int = */
/*mCurrentMusic.type*//*
 0
            val subTitle : String = mCurrentMusic.titleOfChapter()
            val author : String = mCurrentMusic.authorOfBook()
            val bookUrl : String = mCurrentMusic.getAudioUrl()
            val imgUrl : String = mCurrentMusic.coverOfChapter()
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_SHARE_MODULE_SHARE_ACTIVITY)
                .withString(ARouterUrl.KEY_SHARE_BOOK_TITLE, alias)
                .withInt(ARouterUrl.KEY_SHARE_BOOK_TYPE, type)
                .withString(ARouterUrl.KEY_SHARE_BOOK_SUB_TITLE, subTitle)
                .withString(ARouterUrl.KEY_SHARE_BOOK_AUTHOR, author)
                .withString(ARouterUrl.KEY_SHARE_BOOK_URL, bookUrl)
                .withString(ARouterUrl.KEY_SHARE_BOOK_IMAGE_URL, imgUrl)
                .navigation()
        }
        iv_btn_backward.setOnClickListener {
            Kukoo.input.seekBy(-15*1000)
        }
        iv_btn_play.setOnClickListener {
            LoggerManager.d(TAG,"iv_btn_play.setOnClickListener state=${state}")
            when (state) {
                UserWatcher.MusicStateWatcher.STATE_PREPARE,
                UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                UserWatcher.MusicStateWatcher.STATE_SEEKING,
                UserWatcher.MusicStateWatcher.STATE_PLAYING ->{
                    Kukoo.input.pause()
                }
                UserWatcher.MusicStateWatcher.STATE_PAUSE ->{
                    Kukoo.input.start()
                }
                else ->{
                    LoggerManager.e(TAG,"iv_btn_play.setOnClick state=${state} 不响应")
                }
            }
        }
        iv_btn_forward.setOnClickListener {
            Kukoo.input.seekBy(30*1000)
        }
        iv_btn_playlist.setOnClickListener {
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_LIST_ACTIVITY)
                .navigation()
        }
        tv_btn_times.setOnClickListener {
            var newSpeed = UserWatcher.MusicStateWatcher.SPEED_1P0
            when (speed) {
                UserWatcher.MusicStateWatcher.SPEED_1P0 -> {
                    newSpeed = UserWatcher.MusicStateWatcher.SPEED_1P2
                }
                UserWatcher.MusicStateWatcher.SPEED_1P2 -> {
                    newSpeed = UserWatcher.MusicStateWatcher.SPEED_1P5
                }
                UserWatcher.MusicStateWatcher.SPEED_1P5 -> {
                    newSpeed = UserWatcher.MusicStateWatcher.SPEED_2P0
                }
                UserWatcher.MusicStateWatcher.SPEED_2P0 -> {
                    newSpeed = UserWatcher.MusicStateWatcher.SPEED_0P8
                }
                UserWatcher.MusicStateWatcher.SPEED_0P8 -> {
                    newSpeed = UserWatcher.MusicStateWatcher.SPEED_1P0
                }
                else -> {}
            }
            //版本适配
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                Kukoo.input.setSpeed(newSpeed)
            }
        }
        ll_btn_timer.setOnClickListener {
            TimerSelectionPopupWindow.create(root)
                .setListener {
                    Kukoo.input.setTimer(it)
                }.show(ll_btn_timer)
        }
        iv_btn_heart.setOnClickListener {
            switchLikeState(mCurrentMusic)
        }
        //
        seek_bar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            var userProgress = 0

            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    userProgress = progress
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                isSeekBarTracking = true
                tv_time_current.setTextColor(ApplicationContext.getColor(R.color.dialog_btn_text_color_red))
                tv_time_total.setTextColor(ApplicationContext.getColor(R.color.dialog_btn_text_color_red))
                seek_bar.thumb = drawable_thumb_red
                val bounds = seek_bar.progressDrawable.bounds
                seek_bar.progressDrawable = drawable_progress_red
                seek_bar.progressDrawable.bounds = bounds
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                isSeekBarTracking = false
                Kukoo.input.seekTo(userProgress)
                tv_time_current.setTextColor(ApplicationContext.getColor(R.color.common_text_tab_gray))
                tv_time_total.setTextColor(ApplicationContext.getColor(R.color.common_text_tab_gray))
                seek_bar.thumb = drawable_thumb_black
                val bounds = seek_bar.progressDrawable.bounds
                seek_bar.progressDrawable = drawable_progress_black
                seek_bar.progressDrawable.bounds = bounds
            }
        })
        bg_btn_subscribe.setOnClickListener {
            switchSubscription()
        }
        tv_title_first.setOnClickListener {
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_LIST_DETAIL_ACTIVITY)
                .withString(ARouterUrl.KEY_BOOK_ID_STR, ""+ mCurrentMusic.idOfBooks())
                .navigation()
        }
        //
        tv_title_first.requestFocus()
        //tv_title.requestFocus()

        //init
        Kukoo.watcher.register(mlistener)
        Kukoo.watcher.registerTimerWatcher(mTimerlistener)
    }

    private fun setCoverUrl(url:String){
        Monet.get(ApplicationContext.instance())
            .load<GlideConfig>(url)
            .placeholder(R.mipmap.common_icon_default_editor_picks)
            .into(iv_music_icon)
    }

    override fun show() {
        super.show()
        root.setTranslationY(ApplicationContext.dp2px(mAnimHeight).toFloat())
        root.animate().translationY(0f).setDuration(mAnimTime).start()
    }

    override fun dismiss() {
        root.animate()
            .translationY(ApplicationContext.dp2px(mAnimHeight).toFloat())
            .setDuration(mAnimTime)
            .withEndAction(Runnable {
                Kukoo.watcher.unregister(mlistener)
                Kukoo.watcher.unregisterTimerWatcher(mTimerlistener)
                _dismiss()
            })
            .start()
    }

    private fun _dismiss() {
        super.dismiss()
    }

    private val mlistener = object : UserWatcher.MusicStateWatcher{

        override fun onMusicChanged(music: LocalMediaListItemBean) {
            LoggerManager.d(TAG,"onMusicChanged - music.idOfBooks()=${music.idOfBooks()}")
            mCurrentMusic = music
            //
            setCoverUrl(mCurrentMusic.coverOfChapter())
            tv_title.setText(mCurrentMusic.titleOfChapter())
            tv_title_first.setText(mCurrentMusic.titleOfBooks())
            //
            loadSubscribeState(mCurrentMusic)
            loadLikeState(mCurrentMusic)
        }

        override fun onPlayTimeChanged(currentInt:Int, totalInt:Int, current:String, total:String) {
            tv_time_current.setText(current)
            tv_time_total.setText(total)
            if (!isSeekBarTracking) {
                seek_bar.max = totalInt
                seek_bar.progress = currentInt
            }
        }

        override fun onPlayPercentChanged(percent: Int) {}

        override fun onPlayStateChanged(s: Int) {
            state = s
            LoggerManager.d(TAG,"onPlayStateChanged() state=${state}")
            when (state) {
                UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING ->{
                    //无播放内容
                    dismiss()
                }
                */
/*UserWatcher.MusicStateWatcher.STATE_SEEKING,*//*

                UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                UserWatcher.MusicStateWatcher.STATE_PREPARE,
                UserWatcher.MusicStateWatcher.STATE_PLAYING ->{
                    animateCardView(false)
                    iv_btn_play.setImageResource(R.drawable.common_icon_play_stoped2)
                }
                UserWatcher.MusicStateWatcher.STATE_PAUSE ->{
                    animateCardView(true)
                    iv_btn_play.setImageResource(R.drawable.common_icon_play_start)
                }
                else ->{
                    LoggerManager.e(TAG, "mlistener.onPlayStateChanged state=${state} 不响应")
                }
            }
        }

        override fun onPlaySpeedChanged(speed: Float) {
            //
            this@MediaControlerDialog.speed = speed
            when (speed) {
                UserWatcher.MusicStateWatcher.SPEED_1P0 -> {
                    tv_btn_times.setText(com.sense.kukoo.common_i18n.R.string.media_controler_speed_1p0)
                    tv_btn_times.setTextColor(ApplicationContext.getColor(R.color.android_black))
                }
                UserWatcher.MusicStateWatcher.SPEED_2P0 -> {
                    tv_btn_times.setText(com.sense.kukoo.common_i18n.R.string.media_controler_speed_2p0)
                    tv_btn_times.setTextColor(ApplicationContext.getColor(R.color.dialog_btn_text_color_red))
                }
                UserWatcher.MusicStateWatcher.SPEED_1P2 -> {
                    tv_btn_times.setText(com.sense.kukoo.common_i18n.R.string.media_controler_speed_1p2)
                    tv_btn_times.setTextColor(ApplicationContext.getColor(R.color.dialog_btn_text_color_red))
                }
                UserWatcher.MusicStateWatcher.SPEED_1P5 -> {
                    tv_btn_times.setText(com.sense.kukoo.common_i18n.R.string.media_controler_speed_1p5)
                    tv_btn_times.setTextColor(ApplicationContext.getColor(R.color.dialog_btn_text_color_red))
                }
                UserWatcher.MusicStateWatcher.SPEED_0P8 -> {
                    tv_btn_times.setText(com.sense.kukoo.common_i18n.R.string.media_controler_speed_0p8)
                    tv_btn_times.setTextColor(ApplicationContext.getColor(R.color.dialog_btn_text_color_red))
                }
                else -> {}
            }
        }

        override fun onPlayListChanged() {}
    }

    private val mTimerlistener = object : UserWatcher.TimerStateWatcher{
        override fun onTimerChanged(type: Int, left: Long, leftStr:String) {
            if(left<=0){
                iv_btn_timer_text.text = ""
            }else{
                iv_btn_timer_text.text = leftStr
            }
        }
    }

    private var isZoomOutCardView:Boolean = false

    private fun animateCardView(isZoomOut:Boolean){
        if(isZoomOutCardView != isZoomOut){
            isZoomOutCardView= isZoomOut
            if (isZoomOutCardView) {
                zoomOutCardView()
            }else{
                zoomInCardView()
            }
        }
    }

    private fun zoomInCardView(){
        card_view.animate().scaleX(1F).scaleY(1F).setDuration(mAnimTime).start()
    }

    private fun zoomOutCardView(){
        card_view.animate().scaleX(0.8F).scaleY(0.8F).setDuration(mAnimTime).start()
    }

    private fun setSubscribeBtnState(isSub:Boolean){
        if(isSubscribe != isSub){
            isSubscribe = isSub
            if (isSub) {
                //订阅
                bg_btn_subscribe.setImageResource(com.sense.kukoo.common.R.drawable.common_icon2_sub_off_28dp)
            }else{
                //未订阅
                bg_btn_subscribe.setImageResource(com.sense.kukoo.common.R.drawable.common_icon2_sub_on_28dp)
            }
        }
    }

    private fun loadSubscribeState(music: LocalMediaListItemBean){
        if (!login.isLogin()) {
            //未登陆默认为未订阅
            bg_btn_subscribe.visibility = View.VISIBLE
            setSubscribeBtnState(false)
            return
        }
        //订阅状态
        bg_btn_subscribe.visibility = View.GONE
        request {
            val isSubscription = MediaModel().isSubscription("" + music.idOfBooks())
            withContext(Dispatchers.Main){
                if (isSubscription.success) {
                    val isSub: Boolean = isSubscription.data!!
                    //
                    bg_btn_subscribe.visibility = View.VISIBLE
                    setSubscribeBtnState(isSub)
                }else{
                    Log.e(TAG, "result=" + isSubscription.msg)
                    isSubscription.msg.let {
                        ToastUtils.showToast(it)
                    }
                }
            }
        }
    }

    private fun switchSubscription(){
        if (!BottomLoginDialog.autoCheckAndLogin(context)){
            //未登陆不能进行订阅
            return
        }
        request{
            val result = MediaModel().subscription("" + mCurrentMusic.idOfBooks())
            withContext(Dispatchers.Main){
                if (result.success){
                    val isSubscription:Boolean = !isSubscribe
                    setSubscribeBtnState(isSubscription)
                    //通知详情页
                    EventBus.getDefault().post(SubscriptionChangedEvent(mCurrentMusic.idOfBooks(),
                                                                        isSubscription,
                                                                        SubscriptionChangedEvent.FROM_CONTROLER))
                } else {
                    Log.e(TAG, "result=" + result.msg)
                    result.msg.let { ToastUtils.showToast(it) }
                }
            }
        }
    }

    private fun loadLikeState(music: LocalMediaListItemBean){
        //like状态
        if (!login.isLogin()) {
            //未登陆默认为未点赞
            iv_btn_heart.visibility = View.VISIBLE
            setLikeState(false)
            return
        }
        //like状态
        iv_btn_heart.visibility = View.INVISIBLE
        request{
            val isLike = MediaModel().isLike("" + music.idOfBooks(), "" + music.idOfChapter())
            withContext(Dispatchers.Main){
                if (isLike.success) {
                    val isLike: Boolean = isLike.data!!
                    //
                    iv_btn_heart.visibility = View.VISIBLE
                    setLikeState(isLike)
                }else{
                    Log.e(TAG, "result=" + isLike.msg)
                    isLike.msg.let {
                        ToastUtils.showToast(it)
                    }
                }
            }
        }
    }

    private fun switchLikeState(music: LocalMediaListItemBean){
        if (!BottomLoginDialog.autoCheckAndLogin(context)){
            //未登陆不能进行订阅
            return
        }
        request{
            val result = MediaModel().like("" + music.idOfBooks(), "" + music.idOfChapter())
            withContext(Dispatchers.Main){
                if (result.success){
                    val like:Boolean = !isLike
                    setLikeState(like)
                    LoggerManager.e("result.success, like=${like}")
                } else {
                    Log.e(TAG, "result=" + result.msg)
                    result.msg.let { ToastUtils.showToast(it) }
                }
            }
        }
    }

    private fun setLikeState(isL:Boolean){
        if (isLike!=isL){
            isLike = isL
            if(isLike){
                iv_btn_heart.setImageResource(R.drawable.common_icon_heart_red)
            }else{
                iv_btn_heart.setImageResource(R.drawable.common_icon_heart_black)
            }
        }
    }

    private fun <T> request(execute: suspend CoroutineScope.() -> T){
        GlobalScope.launch(Dispatchers.IO){
            try {
                execute()
            }catch (e:Exception){
                e.printStackTrace()
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: SubscriptionChangedEvent) {
        if(event.from != SubscriptionChangedEvent.FROM_CONTROLER && mCurrentMusic.idOfBooks() == event.bookId){
            setSubscribeBtnState(event.isSubscribe)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: LoginSuccessEvent) {
        loadSubscribeState(mCurrentMusic)
        loadLikeState(mCurrentMusic)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: LogoutEvent) {
        loadSubscribeState(mCurrentMusic)
        loadLikeState(mCurrentMusic)
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }


}*/
